package com.xrj4j.car_news

import android.os.Build
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import androidx.annotation.RequiresApi
import androidx.databinding.DataBindingUtil
import com.google.gson.Gson
import com.xrj4j.car_news.adapter.BrandListAdapter
import com.xrj4j.car_news.api.CarApi
import com.xrj4j.car_news.databinding.ActivityBrandListBinding
import com.xrj4j.car_news.model.BrandItem
import com.xrj4j.car_news.model.LogoItem
import com.xrj4j.car_news.model.ResultDto
import com.xrj4j.car_news.utils.RetrofitUtils
import com.xrj4j.car_news.utils.ToastUtils
import retrofit2.Call
import retrofit2.Response

class BrandListActivity : AppCompatActivity() {

    private val binding: ActivityBrandListBinding by lazy {
        DataBindingUtil.setContentView(this, R.layout.activity_brand_list)
    }

    private val dataList = mutableListOf<BrandItem>()

    val adapter: BrandListAdapter by lazy {
        BrandListAdapter(this, dataList)
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_brand_list)

        val extras = intent.extras
        val logoItem = (extras?.get("data") as LogoItem)
        binding.title = logoItem.brand_name
        binding.adapter = adapter

        loadData(logoItem.id)
    }

    private fun loadData(id: String?) {
        val carApi = RetrofitUtils.getApi(CarApi.baseUrl, CarApi::class.java)
        val call = carApi.getBrandList(CarApi.key, id, null)
        val ctx = this
        call.enqueue(object : retrofit2.Callback<ResultDto<BrandItem>> {
            override fun onResponse(
                call: Call<ResultDto<BrandItem>>,
                response: Response<ResultDto<BrandItem>>
            ) {
                ToastUtils.show(ctx, "获取数据成功")
                val result = response.body()
                adapter.addDataList(result?.result)
            }

            override fun onFailure(call: Call<ResultDto<BrandItem>>, t: Throwable) {
                ToastUtils.show(ctx, "获取接口数据失败")
            }
        })
    }
}